/**
 * axios  二次封装
 */
import axios from "axios";
import config from "../config/index";
import { ElMessage } from "element-plus";
import router from "../router";
import Storage from "../utils/storage";
const TOKNE_INVALID = "token 认证失败";
const NETWORK_ERROR = "网络异常";

// 创建实例对象
const service = axios.create({
  baseURL: config.baseApi,
  timeout: 8000,
});
//  请求拦截
service.interceptors.request.use((req) => {
  const headers = req.headers;
  const { token = "" } = Storage.getItem("userInfo") || {};
  if (!headers.Authorization) headers.Authorization = "Bearer " + token;
  return req;
});
//  响应拦截
service.interceptors.response.use((res) => {
  const { code, data, msg } = res.data;
  if (code == 200) {
    return data;
  } else if (code === 40001) {
    ElMessage.error(TOKNE_INVALID);
    setTimeout(() => {
      router.push("/login");
    }, 1500);
    return Promise.reject(TOKNE_INVALID);
  } else if (code === 0) {
    return data;
  } else {
    ElMessage.error(msg || NETWORK_ERROR);
  }
});

function request(options) {
  options.method = options.method || "get";
  if (options.method.toLowerCase() === "get") {
    options.params = options.data;
  }
  if (typeof options.mock != "undefined") {
    config.mock = options.mock;
  }
  if (config.env === "prod") {
    service.defaults.baseURL = config.baseApi;
  } else {
    service.defaults.baseURL = config.mock ? config.mockApi : config.baseApi;
  }
  return service(options);
}
export default request;
